#!/usr/bin/env groovy

pipeline {
    agent any
    environment {
        BASE_WORKSPACE = "$env.WORKSPACE"
        TARGET_BRANCH = "*/develop"
        BUILD_GIT_URL = 'https://gitee.com/SmileSB101/qingqiu-react.git'
        STATIC_RESOURCE_GIT_URL = 'https://gitee.com/SmileSB101/qing-qiu-react-static.git'
        STATIC_RESOURCE_GIT_BRANCH = "with-static-resource"
        DOCKER_REGISTRY = "registry.cn-hangzhou.aliyuncs.com"
        DOCKER_IMAGE_NAME = "registry.cn-hangzhou.aliyuncs.com/fast-hub/qingqiu-site"
        DOCKER_USER_NAME = "zxb891532752"
        DOCKER_PWD = "z9627191063"
    }

    stages {
        stage('Prepare env') {
            steps {
                script {
                    env.BASE_WORKSPACE = "$env.WORKSPACE"
                    env.TIMESTRAP = sh(returnStdout: true, script: 'date +%Y%m%d%H%M%S').trim()
                }

                sh 'printenv'
            }
        }
        stage('Pull Code') {
            steps {
                //git branch: 'master', credentialsId: '22e7957e-d67d-4802-b4ef-8a5f8beab40f', url: 'https://gitee.com/SmileSB101/qingqiu-react.git'
                script {
                    def gitResults = checkout([$class: 'GitSCM', branches: [[name: '*/develop']], extensions: [[$class: 'CleanBeforeCheckout']], userRemoteConfigs: [[credentialsId: '22e7957e-d67d-4802-b4ef-8a5f8beab40f', url: "https://gitee.com/SmileSB101/qingqiu-react.git"]]])
                    gitResults.each { k, v -> env.setProperty(k, v) }

                    env.DOCKER_TAG = "${env.GIT_COMMIT}_T${env.TIMESTRAP}_B${env.BUILD_NUMBER}"

                    println(gitResults)
                    println(env.DOCKER_TAG)
                }
            }
        }
        stage('Install Packages') {
            agent {
                docker {
                    image 'node:14.17.5-alpine3.14'
                //image 'ubuntu:21.10'
                //args '-v /usr/bin/git:/usr/bin/git'
                }
            }
            steps {
                sh """
                node -v
                yarn -v
                yarn install
                """
            }
        }
        stage('Build') {
            agent {
                docker {
                    image 'node:14.17.5-alpine3.14'
                }
            }
            steps {
                //nodejs('node-16'){
                    //sh 'npm i'
                    //sh 'npm run release'
                //}

                sh 'yarn release'
                //archiveArtifacts allowEmptyArchive: true, artifacts: 'dist/publish/**', followSymlinks: false, onlyIfSuccessful: true

                stash includes: 'dist/publish/server/**', name: 'serverStash'
                stash includes: 'dist/publish/static/**', name: 'staticStash'
            }
        }
        stage('Commit static resource files') {
            steps {
                unstash('staticStash')

                dir('dist/git/') {
                    checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [[$class: 'CleanBeforeCheckout']], userRemoteConfigs: [[credentialsId: '22e7957e-d67d-4802-b4ef-8a5f8beab40f', url: "https://gitee.com/SmileSB101/qing-qiu-react-static.git"]]])

                    withCredentials([gitUsernamePassword(credentialsId: '22e7957e-d67d-4802-b4ef-8a5f8beab40f', gitToolName: 'Default')]) {
                        sh "git branch -a | egrep 'remotes/origin/${env.STATIC_RESOURCE_GIT_BRANCH}' && (git checkout ${env.STATIC_RESOURCE_GIT_BRANCH} && git pull) || (git branch '${env.STATIC_RESOURCE_GIT_BRANCH}' && git push origin '${env.STATIC_RESOURCE_GIT_BRANCH}')"

                        sh """
                        cp ../publish/static . -vur

                        git branch -a

                        git config --global user.email "zxb13194889618@outlook.com"
                        git config --global user.name "SmileSB101"

                        git status | egrep 'nothing to commit, working tree clean' && echo 'not need commit this time.' || (git add . && git commit -m 'Add ${env.DOCKER_TAG} static changes,hash is ${env.GIT_COMMIT}' && git push origin HEAD:'${env.STATIC_RESOURCE_GIT_BRANCH}')

                        """
                        //git commit -m "Add ${env.DOCKER_TAG} static changes,hash is ${env.GIT_COMMIT}"
                        //sh "git status | egrep 'nothing to commit, working tree clean' && echo 'not need commit this time.' || git push origin HEAD:'${env.STATIC_RESOURCE_GIT_BRANCH}'"
                    }
                }
            }
        }
        stage('Build Docker') {
            //when { expression { SERVICE_BRANCH ==~ /(refs\/tags\/.*)/ } }
            steps {
                unstash('serverStash')

                dir('dist/publish/server/') {
                    sh 'ls'
                    sh 'docker -v'
                    sh "(echo '${env.DOCKER_PWD}' > ./docker_pwd.txt && cat docker_pwd.txt) | docker login '${env.DOCKER_REGISTRY}' -u='${env.DOCKER_USER_NAME}' --password-stdin"
                    sh "docker build -t ${env.DOCKER_IMAGE_NAME}:${env.DOCKER_TAG} ."
                    sh "docker push ${env.DOCKER_IMAGE_NAME}:${env.DOCKER_TAG}"
                }
            }
        }
    }
    post {
        always {
            sh ''
            cleanWs notFailBuild: true
        }
        success {
            sh ''
        }
        failure {
            sh ''
        }
        cleanup {
            sh ''
            cleanWs notFailBuild: true
        }
    }
}

@NonCPS
def Init() {
    env.SERVICE_NAME = DefineServiceName()
    env.SERVICE_HTTP_URL = ConvertSSHtoUrl()
    env.DOCKER_IMAGE_NAME = DefineImageName()
    env.DOCKER_TAG_NAME = DefineTagName()
    env.DOCKER_IMAGE_FULL_NAME = DefineFullImageName()
}

@NonCPS
def DefineFullImageName() {
    fullName = env.DOCKER_IMAGE_NAME + ':' + env.DOCKER_TAG_NAME
    println('fullName: ' + fullName)
    return fullName.toLowerCase()
}

@NonCPS
def DefineTagName() {
    tagName = env.SERVICE_BRANCH.split('/')[-1] + '-' + env.BUILD_NUMBER
    println('tagName: ' + tagName)
    return tagName.toLowerCase()
}

@NonCPS
def DefineImageName() {
    def imageName = ''
    def serviceName = env.SERVICE_NAME
    if (serviceName == 'ec-mobile-wwwpresentation') {
        imageName = 'ngmwww'
        env.IMAGE_PATH = 'ec/app-mobile'
  }else {
        if (env.IMAGE_NAME) {
            imageName = env.IMAGE_NAME
      }else {
            imageName = serviceName.replace('ec-', '').replace('service', '')
        }
    }
    println('imageName: ' + imageName)
    return imageName
}

@NonCPS
def DefineServiceName() {
    def serviceName = env.GIT_URL.split('/')[-1]
    println "GIT_URL: ${env.GIT_URL}"
    println "serviceName: ${serviceName}"
    serviceName = serviceName.replaceAll('.git', '')
    return serviceName
}

@NonCPS
def ConvertSSHtoUrl() {
    return env.SERVICE_URL.replace('git@git.newegg.org:', 'https://git.newegg.org/')
}

def GetPublishRuntime(neciConfig) {
    if (!neciConfig.publish?.hasProperty('onlyDocker') && neciConfig.publish?.onlyDocker) {
        //读取docker file区别
        def dockerfileLines = GetDockerfileLines()
        def lineNum = dockerfileLines.size() - 1
        for (; lineNum >= 0; lineNum--) {
            def line = dockerfileLines[lineNum]
            if (line.startsWith('FROM')) {
                if (line.indexOf('alpine') > -1) {
                    return ' -r linux-musl-x64 --self-contained false'
                }else {
                    return ' -r linux-x64 --self-contained false'
                }
                break
            }
        }
    }
}

def GetDockerfileLines() {
    def dockerfileText = readFile 'Dockerfile'
    def dockerfileLines = [dockerfileText.split('\n')].flatten().findAll { it != null }
    return dockerfileLines
}

def RewriteDockerfile(neciConfig) {
    def dockerfileLines = GetDockerfileLines()
    def lineNum = dockerfileLines.size() - 1
    for (; lineNum >= 0; lineNum--) {
        def line = dockerfileLines[lineNum]
        if (line.startsWith('FROM')) {
            def baseImageFullName = line.split(' ')[-1]
            def baseImageName = baseImageFullName.split(':')[0]
            def baseImageTag = baseImageFullName.split(':')[-1]
            dockerfileLines.add(lineNum + 1, "ENV BASE_DOCKER_IMAGE_NAME=${baseImageName}")
            dockerfileLines.add(lineNum + 1, "ENV BASE_DOCKER_IMAGE_TAG=${baseImageTag}")
            break
        }
    }
    dockerfileLines.add(lineNum + 1, "ENV BUSINESS_DOCKER_IMAGE_NAME=${DOCKER_IMAGE_NAME}")
    dockerfileLines.add(lineNum + 1, "ENV BUSINESS_DOCKER_IMAGE_TAG_NAME=${DOCKER_TAG_NAME}")
    if (neciConfig?.connection?.department != null) {
        dockerfileLines.add(lineNum + 1, "ENV BUSINESS_OWNER=${neciConfig.connection.department}")
    }
    dockerfileText = dockerfileLines.join('\n')
    echo "${dockerfileText}"
    writeFile file: 'Dockerfile', text: dockerfileText
}

